import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Editor to create and save new boards
 * @author mx109
 *
 */
public class Edytor {
	private class Element{int field=0;int  move=0;}
	private Element elements[][];
	private int x,y;
	private int players=0;
	private int boxes=0;
	private int hole=0;
	@SuppressWarnings("unused")
	private Edytor(){}
	
	/**
	 * Constructor created new editor for board of desired sizes
	 * @param x width of new board
	 * @param y height of new board
	 */
	public Edytor(int x, int y){
		this.x=x;
		this.y=y;
		 elements=new Element[x][y];
		 for (int i=0; i<x; i++)
				for (int j=0; j<y; j++) elements[i][j]=new Element();
	}
	
	/**
	 * Set type of chosen filed.
	 * @param pos position of chosen field
	 * @param T  type of chosen field
	 */
	public void setField(Position pos, Type T){
		switch(T){
		case BOX: elements[pos.x][pos.y].move=1; break;
		case PLAYER: elements[pos.x][pos.y].move=2; break;
		case NOMOVEABLE: elements[pos.x][pos.y].move=0; break;
		case EMPTY: elements[pos.x][pos.y].field=0; break;
		case WALL: elements[pos.x][pos.y].field=2; break;
		case HOLE: elements[pos.x][pos.y].field=1; break;
		}
	}
	
	/**
	 * Checks created board
	 * @throws NoPlayerOnBoard throw this exception if there is any player on board
	 * @throws NotEnoughBoxes throw this exception if the number of boxes is too small
	 */
	public void test() throws NoPlayerOnBoard, NotEnoughBoxes{
		for (int i=0; i<x; i++)
			for (int j=0; j<y; j++){
				if (elements[i][j].move==1) boxes++;
				if (elements[i][j].move==2) players++;
				if (elements[i][j].field==1) hole++;
				}
		if (players==0) throw new NoPlayerOnBoard();
		if (hole!=boxes) throw new NotEnoughBoxes();
	} 
	
	/**
	 * Save created board to chosen file
	 * @param F file to which a board is being save
	 * @throws IOException
	 */
	public void getMap(File F) throws IOException{
		
		if (F.exists()) F.delete();
		F.createNewFile();
		FileWriter fw = new FileWriter(F);
		BufferedWriter bw = new BufferedWriter(fw);
		bw.write(x+"");
		bw.write(" ");
		bw.write(y+"");
		bw.newLine();
		for (int j=0; j<y; j++){
			for (int i=0; i<x; i++){
				bw.write(elements[i][j].field+"");
				bw.write(" ");}
			bw.newLine();}
		
		bw.write(players+"");
		bw.newLine();
		for (int i=0; i<x; i++)
			for (int j=0; j<y; j++)
				if (elements[i][j].move==2){ 
					bw.write(i+"");
					bw.write(" ");
					bw.write(j+"");
					bw.newLine();
					}
		
		bw.write(boxes+"");
		bw.newLine();
		for (int i=0; i<x; i++)
			for (int j=0; j<y; j++)
				if (elements[i][j].move==1) { 
					bw.write(i+"");
					bw.write(" ");
					bw.write(j+"");
					bw.newLine();
					}
		bw.close();
		}
	
}
